package minimips.isa;

import minimips.computer.Computer;
import minimips.exception.StopInstructionException;

public abstract class RegisterWritingInstruction extends Instruction {

	private int destinationRegister;
	
	public RegisterWritingInstruction(long memoryAddress, int opcode,
			String instructionToken) {
		super(memoryAddress, opcode, instructionToken);
	}

	@Override
	protected void fetchInstruction(Computer computer)
			throws StopInstructionException {
		super.fetchInstruction(computer);
		this.destinationRegister = this.getDestinationRegister();
		computer.addRegisterBeingUsed(this.destinationRegister);
	}
	
	protected abstract int getDestinationRegister();

	@Override
	protected void executeInstruction(Computer computer) {
		long aluOperation = this.executeAluOperation(computer);
		computer.getEx_mem_aluOutput().setRegisterValue(aluOperation);	
		computer.putValueInCache(this.destinationRegister, aluOperation);
	}

	protected abstract long executeAluOperation(Computer computer);

	@Override
	protected void executeMemoryAccess(Computer computer) {
		
	}

	@Override
	protected void executeWriteBack(Computer computer) {
		computer.setProgrammableRegisterValue(this.destinationRegister, computer.getMem_wb_aluOutput());
		computer.removeRegisterBeingUsed(this.destinationRegister);
		computer.removeValueInCache(this.destinationRegister);
	}
}
